package http_helper

import (
	"io"
	"net/http"
	"strings"
	"sync"
	"time"
)

type HttpClientHelper struct {
	httpClient http.Client
}

var clientHelper *HttpClientHelper
var once sync.Once

func ClientInstance() *HttpClientHelper {
	once.Do(func() {
		clientHelper = &HttpClientHelper{}
	})
	return clientHelper
}

func (h *HttpClientHelper) setHttpClientTimeout(timeout time.Duration) {
	h.httpClient.Timeout = timeout
}
func (h *HttpClientHelper) Post(url string, contentType string, param string, timeout time.Duration) (error, int, []byte) {
	h.setHttpClientTimeout(timeout)
	resp, err := h.httpClient.Post(url, contentType, strings.NewReader(param))
	if err != nil {
		return err, http.StatusRequestTimeout, []byte("")
	}
	if resp.StatusCode != http.StatusOK {
		return nil, resp.StatusCode, []byte("")
	}
	defer resp.Body.Close()
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return err, http.StatusBadGateway, []byte("")
	}
	return nil, http.StatusOK, body
}
